package com.yape.webCrawler.aop;
import com.yape.dao.ICrawlerLogDao;
import com.yape.po.CrawlerLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Date;

import com.yape.Enum.CrawlerEnum;

import javax.annotation.Resource;

/**
 * @author yape
 * @description
 * @date 2025/5/25 16:28
 */
@Aspect
@Component
@Slf4j
public class CrawlerLogAspect {

    @Resource
    private ICrawlerLogDao crawlerLogDao;

    @Around("@annotation(com.yape.annotation.CrawlerLog)")
    public Object logCrawler(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取目标对象
        Object target = joinPoint.getTarget();
        // 获取@Component注解
        org.springframework.stereotype.Component componentAnno =
                AnnotationUtils.findAnnotation(target.getClass(), org.springframework.stereotype.Component.class);
        String crawlerName = componentAnno != null ? componentAnno.value() : target.getClass().getSimpleName();

        // 查找中文说明
        String crawlerInfo = "";
        for (CrawlerEnum e : CrawlerEnum.values()) {
            if (e.getServiceName().equals(crawlerName)) {
                crawlerInfo = e.getInfo();
                break;
            }
        }

        long start = System.currentTimeMillis();
        // 日志输出
        log.info("============爬虫任务开始============");
        log.info("爬虫服务: {}({})", crawlerName, crawlerInfo);
        log.info("开始时间: {}", new java.util.Date(start));
        Object result = null;
        int dataCount = 0;
        try {
            result = joinPoint.proceed();
            if (result instanceof java.util.Collection) {
                dataCount = ((java.util.Collection<?>) result).size();
            } else if (result != null) {
                dataCount = 1;
            }
            return result;
        } finally {
            long end = System.currentTimeMillis();
            log.info("============爬虫任务完成============");
            log.info("结束时间: {}", new java.util.Date(end));
            log.info("耗时: {} 毫秒", end - start);
            log.info("数据条数: {}", dataCount);
            // 插入日志表
            CrawlerLog crawlerLog = CrawlerLog.builder()
                    .crawlerName(crawlerName)
                    .crawlerInfo(crawlerInfo)
                    .startTime(new java.util.Date(start))
                    .endTime(new java.util.Date(end))
                    .duration(end - start)
                    .dataCount(dataCount)
                    .build();
            crawlerLogDao.insertCrawlerLog(crawlerLog);
        }
    }
}